package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void insert(UserInfo userInfo) {
        userInfoRepository.insert(userInfo);
    }

    @Override
    public void delete(String id) {
        userInfoRepository.deleteById(id);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoRepository.insert(userInfo);
    }

    @Override
    public UserInfo get(String id) {
        //orElse方法从optional中取值，如果取不到返回null
        return userInfoRepository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return userInfoRepository.findAll();
    }

    @Override
    public Boolean checkPhone(String phone) {
        UserInfo u = userInfoRepository.findByPhone(phone);
        return u==null?true:false;
    }

    @Override
    public void sendVerifyCode(String phone, String smsUrl, String appKey) {
        //1:创建验证码, 编辑短信
        String code = UUID.randomUUID().toString().
                replaceAll("-", "").substring(0, 4);
        System.out.println("【验证码】  "+code);
//        StringBuilder sb = new StringBuilder(80);
//        sb.append("【中正云通信】您的验证码是");
//        sb.append(code);
//        sb.append(" 退订回T");
//        String url = smsUrl+"?tos="+phone+"&msg="+sb.toString()+"&appkey="+appKey;
//        System.out.println(url);
//        System.out.println("https://way.jd.com/jixintong/SMSmarketing?tos=13580305095&msg=【中正云通信】您的验证码是8888 退订回T&appkey=7a1577a9f39f5751b511de08419b5b76");
//        //spring提供http请求发送类
//        RestTemplate restTemplate = new RestTemplate();
//        //参数1: 请求url[url中有参数占位符], 参数2:返回值类型, 参数3:请求需要参数
//        //String ret = restTemplate.getForObject(url, String.class,phone,sb.toString(), appKey);
//        String ret = restTemplate.getForObject(url, String.class);
//        System.out.println(ret);
//        if(!ret.contains("Success")){
//            throw new LogicException("短信发送失败");
//        }


        //3:将验证码缓存到redis中
        userInfoRedisService.setVerifyCode(phone, code);

    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        AssertUtil.hasLength(phone, "手机号不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        AssertUtil.isEquals(password, rpassword, "两次输入密码不一致");
        if(!checkPhone(phone)){
            throw new LogicException("手机号已存在");
        }
        //code可能为空，因为有可能redis中存的数据已经过期
        String code = userInfoRedisService.getVerifyCode(phone);
        if(code == null || !code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码错误或已过期");
        }

        //添加到数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password); //假装加密
        userInfo.setLevel(1);
        userInfo.setCity("");
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setInfo("");
        //关键字段建议大家自己控制
        userInfo.setState(UserInfo.STATE_NORMAL);

        save(userInfo);

    }

    public void save(UserInfo u){
        userInfoRepository.save(u);
    }

    @Override
    public UserInfo login(String username, String password) {
        UserInfo u = userInfoRepository.findByPhone(username);
        if(u != null && u.getPassword().equals(password)){
            //登陆成功
            u.setPassword("");
            return u;
        }
        else{
            //登陆失败
            throw new LogicException("用户名或密码错误");
        }
    }
}
